package com.software.loginregister.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.flexbox.FlexboxLayout;
import com.software.loginregister.R;
import com.software.loginregister.adapter.HotFoodAdapter;
import com.software.loginregister.api.WorksApi;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.SearchHistory;

import com.software.loginregister.api.SearchHistoryService;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.Works;
import com.software.loginregister.entity.vo.UserUpdateDTO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SearchActivity extends AppCompatActivity {
    private EditText edtSearch;
    private FlexboxLayout flexboxHistory;
    private RecyclerView rvHotFoods;
    private List<String> searchHistory;
    private List<Works> hotWorkList;
    private HotFoodAdapter hotFoodAdapter;
    private Long currentUserId;
    private SearchHistoryService searchHistoryService;
    private WorksApi worksApi;
    private static final String TAG = "SearchActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        // 获取当前用户ID
        UserUpdateDTO userInfo = SharedPreferencesUtil.getUserInfo(this);
        if (userInfo != null) {
            currentUserId = userInfo.getUserId();
        }

        // 初始化API服务
        searchHistoryService = RetrofitClient.getInstance().create(SearchHistoryService.class);
        worksApi = RetrofitClient.getInstance().create(WorksApi.class);

        // 初始化搜索历史列表
        searchHistory = new ArrayList<>();

        initViews();
        initData();
        setStatusBar();
    }

    private void initViews() {
        edtSearch = findViewById(R.id.edt_search);
        flexboxHistory = findViewById(R.id.flexbox_history);
        findViewById(R.id.btn_search_back).setOnClickListener(v -> finish());
        findViewById(R.id.btn_search).setOnClickListener(v -> performSearch());
        findViewById(R.id.btn_clear_history).setOnClickListener(v -> clearSearchHistory());
        // 初始化热门作品列表
        rvHotFoods = findViewById(R.id.rv_hot_foods);
        rvHotFoods.setLayoutManager(new LinearLayoutManager(this));
        hotFoodAdapter = new HotFoodAdapter(new ArrayList<>());
        rvHotFoods.setAdapter(hotFoodAdapter);
    }

    private void initData() {
        loadSearchHistory();
        loadHotWorks();
    }

    private void loadSearchHistory() {
        if (currentUserId == null) return;
        RetrofitClient.getInstance()
                .create(WorksApi.class)
                .getSearchHistory(currentUserId, 10)
                .enqueue(new Callback<Result<List<SearchHistory>>>() {
                    @Override
                    public void onResponse(Call<Result<List<SearchHistory>>> call,
                                           Response<Result<List<SearchHistory>>> response) {
                        if (response.isSuccessful() && response.body() != null
                                && response.body().getCode() == 1) {
                            searchHistory.clear();
                            // 使用 Set 来去重
                            Set<String> uniqueKeywords = new LinkedHashSet<>();
                            for (SearchHistory history : response.body().getData()) {
                                uniqueKeywords.add(history.getKeyword());
                            }
                            // 转换回List
                            searchHistory.addAll(uniqueKeywords);
                            updateSearchHistory();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<List<SearchHistory>>> call, Throwable t) {
                        Toast.makeText(SearchActivity.this,
                                "加载搜索历史失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void performSearch() {
        String keyword = edtSearch.getText().toString().trim();
        if (!TextUtils.isEmpty(keyword)) {
            // 启动搜索结果活动
            Intent intent = new Intent(this, SearchResultActivity.class);
            intent.putExtra("keyword", keyword);
            intent.putExtra("userId", currentUserId);
            startActivity(intent);
            // 保存搜索历史
            saveSearchHistory(keyword);
        }
    }

    private void saveSearchHistory(String keyword) {
        if (currentUserId == null || TextUtils.isEmpty(keyword)) {
            return;
        }
        SearchHistory history = new SearchHistory();
        history.setUserId(currentUserId);
        history.setKeyword(keyword);
        searchHistoryService.addSearchHistory(history).enqueue(new Callback<Result<Void>>() {
            @Override
            public void onResponse(Call<Result<Void>> call, Response<Result<Void>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getCode() == 1) {
                    if (!searchHistory.contains(keyword)) {
                        searchHistory.add(0, keyword);
                        if (searchHistory.size() > 10) {
                            searchHistory.remove(searchHistory.size() - 1);
                        }
                        updateSearchHistory();
                    }
                }
            }

            @Override
            public void onFailure(Call<Result<Void>> call, Throwable t) {
                Toast.makeText(SearchActivity.this, "保存搜索历史失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setStatusBar() {
        Window window = getWindow();
        // 设置状态栏背景为透明
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        // 设置状态栏文字颜色为深色
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);

    }

    private void loadHotWorks() {
        worksApi.getHotWorks().enqueue(new Callback<Result<List<Map<String, Object>>>>() {
            @Override
            public void onResponse(Call<Result<List<Map<String, Object>>>> call,
                                   Response<Result<List<Map<String, Object>>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Result<List<Map<String, Object>>> result = response.body();
                    if (result.getCode() == 1 && result.getData() != null) {
                        hotFoodAdapter.updateData(result.getData());
                    } else {
                        Log.e(TAG, "加载热门作品失败: " + result.getMsg());
                        Toast.makeText(SearchActivity.this,
                                "加载热门作品失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.e(TAG, "服务器响应错误: " + response.code());
                    Toast.makeText(SearchActivity.this,
                            "加载热门作品失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result<List<Map<String, Object>>>> call, Throwable t) {
                Log.e(TAG, "网络请求失败", t);
                Toast.makeText(SearchActivity.this,
                        "网络连接失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateSearchHistory() {
        flexboxHistory.removeAllViews();
        for (String history : searchHistory) {
            TextView textView = (TextView) getLayoutInflater()
                    .inflate(R.layout.item_search_history, flexboxHistory, false);
            textView.setText(history);
            textView.setOnClickListener(v -> {
                edtSearch.setText(history);
                performSearch();
            });
            flexboxHistory.addView(textView);
        }
    }

    private void clearSearchHistory() {
        if (currentUserId == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        RetrofitClient.getInstance()
                .create(WorksApi.class)
                .clearSearchHistory(currentUserId)
                .enqueue(new Callback<Result<Void>>() {
                    @Override
                    public void onResponse(Call<Result<Void>> call, Response<Result<Void>> response) {
                        if (response.isSuccessful() && response.body() != null
                                && response.body().getCode() == 1) {
                            searchHistory.clear();
                            updateSearchHistory();
                            Toast.makeText(SearchActivity.this,
                                    "清除历史成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(SearchActivity.this,
                                    "清除历史失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Void>> call, Throwable t) {
                        Toast.makeText(SearchActivity.this,
                                "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次返回页面时重新加载数据
        loadSearchHistory();
        loadHotWorks();  // 也重新加载热门作品
    }


}